package com.demo.dao;

import com.demo.pojo.MongoInfo;
import com.demo.pojo.Tag;
import com.demo.pojo.User;
import com.mongodb.BasicDBObject;
import com.mongodb.WriteResult;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author mifei
 * @create 2020-03-30 9:41
 **/
@Component
public class CRUDdao {

    @Autowired
    private MongoTemplate mongoTemplate;
    private String collectionName = "a";

    /**
     * 创建对象
     *
     * @param user
     */
    public void saveUser(User user) {
        mongoTemplate.save(user);
    }

    /**
     * 模糊查询
     */
    public Object findLike(String userName) {
        Pattern pattern = Pattern.compile(".*?" + escapeSpecialWord(userName) + ".*");
        Criteria c5 = Criteria.where("basicInfo.contact").is("陈芳燕");
        c5.and("basicInfo.applicant").regex(pattern);
        Query query = new Query();
        query.addCriteria(c5);
        List<Map> cde_item_v3 = mongoTemplate.find(query, Map.class, "cde_item_v3");
        return cde_item_v3;
    }

    //regex对输入特殊字符转义
    private String escapeSpecialWord(String keyword) {
        if (StringUtils.isNotBlank(keyword)) {
            String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }

    /**
     * 根据用户名查询对象
     */
    public User findOne (String userName) {
        Query query = new Query(Criteria.where("userName").is(userName));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }

    public void findAll(String userName) {
        Query query = new Query();
        for (int i = 1; i < 10000; i++) {
            try{
                System.out.println(i*1);
                List<MongoInfo> list = mongoTemplate.find(query.skip(i-1).limit(1), MongoInfo.class,"cde_item_v3");
                System.out.println(list.get(0).getId());
            }catch (Exception e){
                e.printStackTrace();
                System.out.println(i);
            }
        }
    }

    /**
     * 更新对象
     *
     * @param user
     */
    public long updateUser(User user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
        //更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, User.class);

//		//数据存在就更新，不存在就插入数据
//		UpdateResult result = mongoTemplate.upsert(query, update, User.class);

        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
        if (result != null)
            return result.getMatchedCount();
        else
            return 0;
    }

    /**
     * 删除对象
     *
     * @param id
     */
    public void deleteUserById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, User.class);
    }

    /**
     * 修改tags数组中内嵌文档指定一个元素的值
     * {
     * "_id" : "195861",
     * "tags" : [
     * {
     * "tagId" : NumberLong(766),
     * "optDate" : ISODate("2013-08-12T15:21:02.930Z"),
     * "enable" : true
     * },
     * {
     * "tagId" : NumberLong(778),
     * "optDate" : ISODate("2013-08-12T15:21:02.930Z"),
     * "enable" : true
     * }
     * ]
     * }
     */
    public void embedUdate(String id, Long tagId) {
        Query query = Query.query(Criteria.where("_id").is(id)
                .and("tags.tagId").is(tagId));
        Update update = new Update();
        update.set("tags.$.enable", false);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, collectionName);
    }

    /**
     * 内嵌
     * 给tags数组添加一个元素
     */
    public void embedAddTag(String id, Long tagId) {
        Tag tag = new Tag();
        tag.setTagId(tagId);
        tag.setOptDate(new Date());
        tag.setEnable(true);
        Query query = Query.query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.addToSet("tags", tag);
        UpdateResult upsert = mongoTemplate.upsert(query, update, collectionName);
    }

    /**
     * 内嵌
     * 删除tags数组中指定的内嵌文档
     */
    public void embedRemoveTag(String id, Long tagId) {
        Query query = Query.query(Criteria.where("_id").is(id)
                .and("tags.tagId").is(tagId));
        Update update = new Update();
        update.unset("tags.$");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, collectionName);
    }

    /**
     * 内嵌
     * 删除tags数组中指定的内嵌文档
     */
    public void embedRemoveTag2(String id, Long tagId) {
        Query query = Query.query(Criteria.where("_id").is(id)
                .and("tags.tagId").is(tagId));
        BasicDBObject s = new BasicDBObject();
        s.put("tagId", tagId);
        Update update = new Update();
        update.pull("tags",s);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, collectionName);
    }

}
